/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package FormController;

import PropertiesController.BaseModuleProperties;
import Util.Log;
import Util.TranslatorUtils;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import th.co.tac.esv.tel.ejb.dat.tpt.OutputTemplate;

/**
 *
 * @author Peat
 */
public class BaseFormController extends AbstractController {

    // servlet meta data
    protected final Log log;
    private final String majorServiceId;

    protected BaseModuleProperties mProperty;

    private Map<String, Method> methods = new HashMap<String, Method>();

    protected BaseFormController(String modulePropertiesResourceName,
            Logger logger, Logger transLogger) {
        Class c = this.getClass();

        mProperty = new BaseModuleProperties(modulePropertiesResourceName);

        this.majorServiceId = mProperty.getModulePath();
        this.log = new Log(logger, transLogger);

        for (Method m : c.getDeclaredMethods()) {
            methods.put(m.getName(), m);
        }
    }

    @Override
    protected ModelAndView handleRequestInternal(
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        ModelAndView mv = new ModelAndView("application/console/ajax_response");
        
        try {
            /**
             * Authentication handles (depend on configuration)
             */

            // Rourting to a function param("fnc").'_Console';
            String fnc = request.getParameter("fnc");
            if (fnc==null) {
                throw new Exception("Unsupported fnc: " + fnc);
            }

            String consoleName = fnc + "_Console";
            Method invoker = (Method) methods.get(consoleName);
            if (invoker==null) {
                throw new Exception("Unsupported fnc: " + consoleName);
            }
            mv = (ModelAndView) invoker.invoke(this, mv, request, response);

        } catch (Exception e) {
            // handle Error
            JSONObject result = new JSONObject();

            result.put("result", false);
            result.put("exception", TranslatorUtils.toJSON(e));

            mv.addObject("result", result.toString());
        }
        response.setContentType("application/json");
        return mv;
    }

    protected void handledOutputTemplate(boolean result, OutputTemplate outputTemplate) {
        
    }
}
